import time
import datetime
import base64
import hashlib
from Crypto.Cipher import AES
import string
import uuid
import random
from hashlib import sha256
from urllib import parse
from faker import Faker
from utils.log_handler import logger
from utils.yaml_handler import yamler
from config import settings


class DebugTalk(object):
    # 获取api相关的配置文件参数
    @staticmethod
    def read_config(key):
        data = yamler.read_data(settings.API_CONFIG_PATH, key)
        return data

    # 获取从响应中提取的数据
    @staticmethod
    def get_extract_data(key):
        path = settings.EXTRACT_RES_FILE_PATH
        try:
            yaml_data = yamler.read_data(path, key)
            if "token" in key:
                if yaml_data.count(".") >= 3:
                    data = "Bearer " + yaml_data
                else:
                    data = yaml_data
            else:
                data = yaml_data
            return data
        except Exception as e:
            logger.error(f"获取extract.yaml文件指定key失败：{e}")

    # 获取长度为length的随机数
    @staticmethod
    def random_num(length):
        if not length:
            length = 2
        length = int(length)
        max_num = 10 ** length - 1
        return str(random.randint(0, max_num))

    # @staticmethod
    # def rand_str(len_start=None, len_end=None) -> str:
    #     """生成随机字符串， 如
    #         ${rand_str()}  得到32位字符串
    #         ${rand_str(3)}  得到3位字符串
    #         ${rand_str(3, 10)}  得到3-10位字符串
    #     """
    #     uuid_str = str(uuid.uuid4()).replace('-', '')
    #     if not len_start and not len_end:
    #         return uuid_str
    #     if not len_end:
    #         return uuid_str[:len_start]
    #     else:
    #         return uuid_str[:random.randint(len_start, len_end)]

    @staticmethod
    def random_str(len_start=None, len_end=None):
        """生成随机字符串， 如
                ${rand_str()}  得到32位字符串
                ${rand_str(3)}  得到3位字符串
                ${rand_str(3, 10)}  得到3-10位字符串
        """
        strings = string.ascii_letters + string.digits
        rand_str = "".join(random.sample(strings, 32))
        if not len_start and not len_end:
            return rand_str
        if not len_end:
            return rand_str[:len_start]
        else:
            return rand_str[:random.randint(len_start, len_end)]

    # AES128 CBC PKCS5Padding加密
    @staticmethod
    def aes_encrypt(text, salt, iv):
        block_size = 16

        # 数据进行 PKCS5Padding 的填充
        def pad(pad_text):
            return pad_text + (block_size - len(pad_text) % block_size) * chr(block_size - len(pad_text) % block_size)

        data = pad(text)
        print(data)
        # 创建加密对象
        cipher = AES.new(salt.encode(), AES.MODE_CBC, iv.encode())
        # 得到加密后的字节码
        encrypted_text = cipher.encrypt(bytes(data, 'utf-8'))
        # base64 编码
        encode_text = base64.b64encode(encrypted_text)
        return encode_text.decode('utf-8')

    # md5加密
    @staticmethod
    def md5_encrypt(val):
        return hashlib.md5(str(val).encode("utf-8")).hexdigest()

    # 生成随机密钥
    @staticmethod
    def generate_secret_key():
        sha = sha256()
        sha.update(str(uuid.uuid4()).encode())
        return sha.hexdigest()

    @staticmethod
    def get_timestamp(str_len=13):
        """get timestamp string, length can only between 0 and 16"""
        if isinstance(str_len, int) and 0 < str_len < 17:
            return str(time.time()).replace(".", "")[:str_len]

        raise Exception("timestamp length can only between 0 and 16.")

    @staticmethod
    def get_current_date(fmt="%Y-%m-%d"):
        """get current date, default format is %Y-%m-%d"""
        return datetime.datetime.now().strftime(fmt)

    # 将请求参数进行urlencoded
    @staticmethod
    def uri_encoded(val):
        return parse.quote(val)


faker_obj = Faker(locale="zh_CN")
